class FragmentsController < ApplicationController
  
  def new
  end
  
  def create
    @fragment = Fragment.new params[:fragment]
    @fragment.user_id=session[:user_id] if session[:user_id]
	@fragment.chapter_id = params[:chapter_id]
    begin
      @fragment.save!
	  respond_to do |format|
		format.html { render "fragments/simple_fragment",:layout => false}
		#format.json {render :json=>@fragment.to_json}
	  end	
    rescue Exception=>detail
	  puts "-------------Error #{detail}"
      @fragment
      @novel = @fragment.novel
    end
  end

  def show
    @fragment = Fragment.find params[:id]
  end

  def edit
    @fragment = Fragment.find params[:id]
    if request.post?
      begin
        @fragment.update_attribute :content, params[:fragment][:content]
        @fragment.save!
        redirect_to :action=>"show", :id=>@fragment
      rescue Exception=>detail
        puts "Edit the fragment failed. #{detail.message}"
        @fragment
      end
    else  # send to edit page
      @fragment
    end

  end

  def list
  end

  def vote
    @fragment = Fragment.find params[:id]
    return unless @fragment
    if  session[:user_id].nil?
      return render :js=>"alert('登录后才能投票!');" # Only login user can vote for fragments
    end
    #One user can only vote for one time per one fragment
	#Allow user vote on one fragment multi times.
    #return render(:js=>"alert('你投过票了，是好是坏都不要投了！');") #if Vote.find_by_fragment_id @fragment, :conditions=>["user_id=?", session[:user_id]]

    #Vote 
    add_vote
	
    if @fragment.can_be_merged and @fragment.novel.linkrule==Novel::LINK_RULE_3_DESC
      merge_to_novel @fragment
      flash[:message]="The fragment is merged to novel";
      redirect_to :controller=>"novel", :action=>"show", :id=>@fragment.novel
    else
      if request.xhr?
        @vote_display_id = params[:id].to_s+"_level_"+params[:level] #use to update the vote number
        @vote_number = Vote.count:conditions=>["fragment_id=? and level=?", @fragment.id, params[:level].to_i]
		respond_to do |format|
			format.json { render :json => [@vote_display_id,@vote_number] }  
		end	  
		
      else
        #If not an xhr request, just redirect to show
        redirect_to :controller=>"fragment", :action=>"show", :id=>@fragment
      end
    end

  end


  def merge
    @fragment = Fragment.find params[:id]
    merge_to_novel @fragment
    redirect_to :controller=>"novel", :action=>"show", :id=>@fragment.novel
  end

  private

  def merge_to_novel  fragment
    begin
      if @fragment.fragment_number==@fragment.novel.fragment_number
        merge_fragment_to_novel() if @fragment.fragment_number==@fragment.novel.fragment_number
      else
        flash[:message] = "Can't meged it to novel.This fragment is expired";
      end
    rescue Exception=>detail
      puts "Merge fragment failed. #{detail.message}"
    end
  end

  def merge_fragment_to_novel
    #Do all of this in a transaction
    ActiveRecord::Base.transaction do
      @fragment.update_attribute :merge, Fragment::FRAGMENT_MERGE
      @merge_history = MergeHistory.new :novel_id=>@fragment.novel.id, :fragment_number=>@fragment.novel.fragment_number, :fragment_id=>@fragment.id
      @merge_history.save!
      @fragment.novel.increment! :fragment_number
    end
  end

  def add_vote
    vote = Vote.new
    vote.fragment_id=@fragment.id
    vote.level= params[:level].to_i
	vote.comment = params[:comment]
    vote.user_id= session[:user_id] if session[:user_id]
    begin
      vote.save!
    rescue  Exception=>detail
      puts "Vote failed! #{detail.message}"
    end
  end
end
